import { Injectable } from '@nestjs/common';
import { MailDbService } from './mail.db.services';
import * as nodemailer from 'nodemailer';
import * as _ from 'lodash';
import { MessageGateway } from '../../services/websocket.service';



@Injectable()
export class MailerService {
    constructor(
        public mailDbService: MailDbService,
        public messageGateway:MessageGateway,
    ) { }
    fromMail: string = '350559162@qq.com';
    swig = require("swig");
    date;
    header: Array<any>;
    transporter = nodemailer.createTransport({
        service: 'qq', // 使用了内置传输发送邮件 查看支持列表：https://nodemailer.com/smtp/well-known/
        port: 465, // SMTP 端口
        secureConnection: true, // 使用了 SSL
        auth: {
            user: '350559162@qq.com',
            // 这里密码不是qq密码，是你设置的smtp授权码
            pass: 'ciunamvbmxedcaii',
        }
    });

    async send(params) {
        const mailList = await this.mailDbService.find();//获取数据库中的邮箱列表
        if (mailList && mailList[0] && mailList[0].userMail) {
            let sendList = mailList[0].userMail;//获取邮箱列表
            //获取表格结构
            this.header = params.header;//获取表头
            const content = params.content;//获取列表
            this.date = params.date;//获取日期
            const index = this.header.indexOf('姓名');//名字在第几个
            _.forEach(content, item => {//遍历表格里面的名字，如果名字在数据库的邮箱里面有这个属性并且有值
                if (sendList[item[index]]) {
                    let mailOptions = {
                        from: this.fromMail, // sender address
                        to: sendList[item[index]], // list of receivers
                        subject: `${this.date}工资账单明细`, // Subject line
                        html: this.mailHtmlTemplate(item) // html body
                    };
                    this.sendMail(mailOptions, item[index]);
                }else{//没有邮箱
                    this.messageGateway.emit({
                        type:1,//1是没有邮箱
                        name:item[index]
                    });
                }
            })
            return {msg:'发送中',success:true}
        }else{
            return {msg:'没有添加邮箱',success:false}
        }
    }

    mailHtmlTemplate(content) {
        const outputString = this.swig.renderFile('src/public/tpl.html',
            { headers: this.header, contents: content, date: this.date }
        );
        return outputString;
    }

    async sendMail(mailOptions, name) {
            this.transporter.sendMail(mailOptions, (error, info) => {
                if (error) {
                    this.messageGateway.emit({
                        type:2,//1是失败
                        name:name
                    });
                    return console.log(error);
                }
                this.messageGateway.emit({
                    type:3,//1是成功
                    name:name
                });
            });
    }
}

